//
//  RecViewController.m
//  TravelEveryDay
//
//  Created by dlios on 15-10-15.
//  Copyright (c) 2015年 com.lanou3g. All rights reserved.
//

#import "RecViewController.h"
#import "HADirect.h"
#import "BaseHeader.h"
#import "RecStoryCollectionViewCell.h"
#import "RecStoryModel.h"
#import "RecStoryUserModel.h"
#import "RecTravelNotesTableViewCell.h"
#import "RecTraverNotesModel.h"
#import "RecTravelNotesUserModel.h"
#import "RecAllStoryViewController.h"
#import "RecStoryDetailsViewController.h"
#import "RecTravelNotesDetailsViewController.h"
#import "RecSearchViewController.h"
#import "RecImageWebViewController.h"
#import "RecSubjectModel.h"
#import "RecSubjectTableViewCell.h"

@interface RecViewController ()<UITableViewDataSource, UITableViewDelegate,UICollectionViewDataSource, UICollectionViewDelegate>

@end

@implementation RecViewController
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [NSThread sleepForTimeInterval:1];   //设置进程停止1秒
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //设置返回按钮的颜色及文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.backBarButtonItem = barButtonItem;
    
    self.view.backgroundColor = [UIColor colorWithRed:251/255. green:246/255. blue:233/255. alpha:1];
    _bigImageArr = [[NSMutableArray alloc] init];
    _storyArr = [[NSMutableArray alloc] init];
    _storyUserArr = [[NSMutableArray alloc] init];
    _travelNotesArr = [[NSMutableArray alloc] init];
    _travelNotesUserArr = [[NSMutableArray alloc] init];
    _subjectArr = [[NSMutableArray alloc] init];
    _typeArr = [[NSMutableArray alloc] init];
    _refreshArr = [[NSMutableArray alloc] init];
    _subArr = [[NSMutableArray alloc] init];
    _descArr = [[NSMutableArray alloc] init];
    _imageViewArr = [[NSMutableArray alloc] init];
    _webUrlArr = [[NSMutableArray alloc] init];
    
    [self setUpPage];
    //判断网络调取获取数据方法
    if ([self haveOrNot] == NO) {
     // [self getNextData];
    }else{
        [self addHeader];
        [self addFooter];
    }
}

//tableview页面创建
-(void)setUpPage
{
    _table = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    _table.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];

    _table.separatorColor = [UIColor clearColor];
    [self.view addSubview:_table];
    
    //搜索按钮
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    searchButton.layer.cornerRadius = 15;
    searchButton.layer.masksToBounds = YES;
    [searchButton setTitle:@"搜索国家、城市、景区、游记名" forState:UIControlStateNormal];
    searchButton.frame = CGRectMake(0, 0, 300, 30);
    [searchButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    searchButton.backgroundColor = [UIColor colorWithRed:39/255. green:140/255. blue:155/255. alpha:1];
    [searchButton addTarget:self action:@selector(pushToSearch) forControlEvents:UIControlEventTouchUpInside];
    //将搜索按钮放到titleView上
    self.navigationItem.titleView = searchButton;
}
//点击进入搜索页
-(void)pushToSearch
{
    RecSearchViewController *search = [[RecSearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
}
//故事collectionView页面创建
-(void)setUpCollectionView
{
    //flowLayout设置
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake(160 * WIDTH, 230 * HEIGHT);
    flow.minimumInteritemSpacing = 10;
    flow.minimumLineSpacing = 10;
    [flow setSectionInset:UIEdgeInsetsMake(20 * HEIGHT, 20 * WIDTH, 20 * HEIGHT, 20 * WIDTH)];
    
    //collectionView创建
    _collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 500 * HEIGHT) collectionViewLayout:flow];
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.scrollEnabled = NO;
    _collection.backgroundColor = [UIColor colorWithRed:251/255. green:246/255. blue:233/255. alpha:1];
    //注册cell
    [_collection registerClass:[RecStoryCollectionViewCell class] forCellWithReuseIdentifier:@"collectionCell"];
    
}
#pragma mark - collection Delegate & DataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 4;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    RecStoryModel *model = [_storyArr objectAtIndex:indexPath.row];
    RecStoryUserModel *userModel = [_storyUserArr objectAtIndex:indexPath.row];
    
    RecStoryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell" forIndexPath:indexPath];
    [cell getData:model];
    [cell getUserData:userModel];
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    RecStoryModel *model = [_storyArr objectAtIndex:indexPath.row];
    RecStoryUserModel *userModel = [_storyUserArr objectAtIndex:indexPath.row];
    RecStoryDetailsViewController *storyDetails = [[RecStoryDetailsViewController alloc] init];
    [self.navigationController pushViewController:storyDetails animated:YES];
    storyDetails.myId = model.spot_id;
    storyDetails.userModel = userModel;
}
#pragma mark - tableview Delegate & DataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else {
        return _travelNotesArr.count;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
//设置section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50 * HEIGHT;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00001;
}
//自定义section
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50 * HEIGHT)];
    headerView.backgroundColor = [UIColor colorWithRed:251/255. green:246/255. blue:233/255. alpha:1];
    
    //section标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(30 * WIDTH, 10 * HEIGHT, 150 * WIDTH, 30 * HEIGHT)];
    titleLabel.font = [UIFont boldSystemFontOfSize:18.];
    [headerView addSubview:titleLabel];
    
    //蓝色竖条
    UIView *blueView = [[UIView alloc] initWithFrame:CGRectMake(10* WIDTH, 10 * HEIGHT, 10* WIDTH, 30 * HEIGHT)];
    blueView.backgroundColor = [UIColor colorWithRed:62/255 green:176/255. blue:193/255. alpha:1];
    blueView.layer.cornerRadius = 2.;
    [headerView addSubview:blueView];
    
    //全部按钮创建
    UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [moreButton setTitle:@"全部 ＞" forState:UIControlStateNormal];
    [moreButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    moreButton.alpha = 0.6;
    moreButton.frame = CGRectMake(290 * WIDTH, 10 * HEIGHT, 70* WIDTH, 30 * HEIGHT);
    [moreButton addTarget:self action:@selector(allButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    titleLabel.alpha = 0.8;
    //section字
    if (section == 0) {
        titleLabel.text = @"每日精选故事";
        [headerView addSubview:moreButton];
    }else{
        titleLabel.text = @"精彩游记";
    }
    return headerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 500 * HEIGHT;
    }else{
        return 220 * HEIGHT;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *collectionCellID = @"collectionCell";
        UITableViewCell *collectionCell = [tableView dequeueReusableCellWithIdentifier:collectionCellID];
        if (!collectionCell) {
            collectionCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:collectionCellID];
        }
        [collectionCell addSubview:_collection];
        return collectionCell;
    }else{
            RecTraverNotesModel *model = [_travelNotesArr objectAtIndex:indexPath.row];
            RecTravelNotesUserModel *userModel = [_travelNotesUserArr objectAtIndex:indexPath.row];
            static NSString *cellID = @"cell";
            RecTravelNotesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[RecTravelNotesTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            }
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            cell.backgroundColor = [UIColor colorWithRed:251/255. green:246/255. blue:233/255. alpha:1];
            [cell getData:model];
            [cell getUserData:userModel];
            return cell;
     }
    }
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecTravelNotesUserModel *userModel = [_travelNotesUserArr objectAtIndex:indexPath.row];
    RecTraverNotesModel *model = [_travelNotesArr objectAtIndex:indexPath.row];
    RecTravelNotesDetailsViewController *notesDetails = [[RecTravelNotesDetailsViewController alloc] init];
    [self.navigationController pushViewController:notesDetails animated:YES];
    notesDetails.myId = model.myId;
    notesDetails.model = userModel;
    notesDetails.avatar_l = userModel.avatar_l;
    notesDetails.name = userModel.name;
}
#pragma mark - 数据获取
-(void)getData:(NSString *)str upOrDown:(BOOL)upOrDown
{
    [Refresh getdataWithString:[NSString stringWithFormat:@"http://api.breadtrip.com/v5/index%@",str] block:^(id block) {
        if (upOrDown == NO) {
            [_travelNotesArr removeAllObjects];
            [_travelNotesUserArr removeAllObjects];
            [_storyArr removeAllObjects];
            [_storyUserArr removeAllObjects];
            [_bigImageArr removeAllObjects];
            
        }
        [self getMyData:block];
        _table.delegate = self;
        _table.dataSource = self;
        _table.tableHeaderView =  self.mainScorllView;

        //collectionView创建
        [self setUpCollectionView];
    }];
    
}
#pragma mark - 无网时数据获取
-(void)getNextData
{
    NSURLCache *cache = [[NSURLCache alloc] init];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.breadtrip.com/v5/index/"]];
    //获取缓存
    NSCachedURLResponse *response = [cache cachedResponseForRequest:request];
    
    if (response.data != nil) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response.data options:NSJSONReadingMutableContainers error:nil];
        
        [self getMyData:dic];
    }
    _table.delegate = self;
    _table.dataSource = self;
    [_table reloadData];
    _table.tableHeaderView =  self.mainScorllView;
    
    //collectionView创建
    [self setUpCollectionView];
}
#pragma mark - 刷新,加载
-(void)addHeader
{
    __block RecViewController *rec = self;
    [_table addLegendHeaderWithRefreshingBlock:^{
        rec.upOrDown = NO;
        [rec getData:@"" upOrDown:rec.upOrDown];
    }];
    [_table.header beginRefreshing];
}
-(void)addFooter
{
    __block RecViewController *rec = self;
    [_table addLegendFooterWithRefreshingBlock:^{
        NSString *str = [NSString stringWithFormat:@"?next_start=%@", [rec.refreshArr lastObject]];
        
        rec.upOrDown = YES;
        [rec getData:str upOrDown:rec.upOrDown];
    }];
}

#pragma mark - 全部按钮点击方法
-(void)allButtonClick
{
    RecAllStoryViewController *all = [[RecAllStoryViewController alloc] init];
    [self.navigationController pushViewController:all animated:YES];
}
#pragma mark - 数据解析
-(void)getMyData:(NSDictionary *)myDic
{
    for (NSDictionary *dic in [myDic objectForKey:@"elements"]) {
        
        self.type = [dic objectForKey:@"type"];
        [_typeArr addObject:self.type];
        
        NSString *desc = [dic objectForKey:@"desc"];
        [_descArr addObject:desc];
        
        //刷新所需拼接的字符串
        NSString *refreshStr = [myDic objectForKey:@"next_start"];
        [_refreshArr addObject:refreshStr];
        
        
        //轮播图数据获取
        if ([self.type.stringValue isEqualToString:@"1"]) {
            for (NSDictionary *bigImageDic in [[dic objectForKey:@"data"]objectAtIndex:0]) {
                
                //轮播图图片
                NSString *str = [bigImageDic objectForKey:@"image_url"];
                [_bigImageArr addObject:str];
                //轮播图web数据
                NSString *url = [bigImageDic objectForKey:@"html_url"];
                [_webUrlArr addObject:url];
                
            }
        }
        //故事数据获取
        if ([self.type.stringValue isEqualToString:@"10"]) {
            for (NSDictionary *dataDic in [dic objectForKey:@"data"]) {
                RecStoryModel *model = [RecStoryModel modelWithDictionary:dataDic];
                [_storyArr addObject:model];
                
                RecStoryUserModel *userModel = [RecStoryUserModel modelWithDictionary:[dataDic objectForKey:@"user"]];
                [_storyUserArr addObject:userModel];
            }
        }
        
        //游记数据获取
        if ([desc isEqualToString:@"热门游记"]) {
            for (NSDictionary *dataDic in [dic objectForKey:@"data"]) {
                RecTraverNotesModel *model = [RecTraverNotesModel modelWithDictionary:dataDic];
                [_travelNotesArr addObject:model];
                
                RecTravelNotesUserModel *userModel = [RecTravelNotesUserModel modelWithDictionary:[dataDic objectForKey:@"user"]];
                [_travelNotesUserArr addObject:userModel];
            }
        }
        
        [_table reloadData];
        [_table.header endRefreshing];
        [_table.footer endRefreshing];
    }
    
    //轮播图创建
    
    //        HADirect *hadirect = [HADirect direcWithtFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200 * HEIGHT) ImageArr:_bigImageArr AndImageClickBlock:^(NSInteger index) {
    //
    //        }];
    //
    //        _table.tableHeaderView = hadirect;
    
    //装自定义view的数组
    NSMutableArray *viewsArray = [@[] mutableCopy];
    
    for (int i = 0; i < _bigImageArr.count; ++i) {
        UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
        [image sd_setImageWithURL:[NSURL URLWithString:[_bigImageArr objectAtIndex:i]] placeholderImage:PLACEHOLDERIMAGE];
        [viewsArray addObject:image];
    }
    
    //轮播图循环时间,大小
    self.mainScorllView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200) animationDuration:4];
    
    self.mainScorllView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
        return viewsArray[pageIndex];
    };
    //图片个数
    __block RecViewController *rec = self;
    self.mainScorllView.totalPagesCount = ^NSInteger(void){
        return rec.bigImageArr.count;
    };
    
    //点击图片的block
    self.mainScorllView.TapActionBlock = ^(NSInteger pageIndex){
        RecImageWebViewController *image = [[RecImageWebViewController alloc] init];
        [rec.navigationController pushViewController:image animated:YES];
        image.url = [rec.webUrlArr objectAtIndex:pageIndex];
    };

}
#pragma mark - 判断网络状态
-(BOOL)haveOrNot
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            return NO;
            break;
        case ReachableViaWWAN:
            return YES;
            break;
        case ReachableViaWiFi:
            return YES;
            break;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
